﻿using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Widget;
using AndroidX.AppCompat.App;

using System;
using System.Collections.Generic;

namespace Client.AndroiD
{
    // 1 无法用安卓编译器进行打包 -- 2022-07-27 17:39:15 不知为何又可以了.........
    // 2 在 idata 9105 中运行 接收信息-开启服务 第一次运行会闪退 (未捕获异常信息) -- 已加上日志
    
    // TODO 在 Zebra 设置运行时, 自动加上配置


    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true, LaunchMode = Android.Content.PM.LaunchMode.SingleInstance)]
    public class MainActivity : AppCompatActivity
    {
        public const string KEY_RECEIVE = "receive from scanner";

        public const string SERVICE_STARTED_KEY = "has_service_been_started";

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);

            initUI();
            initEvent();
        }

        protected override void OnPause()
        {
            if (mReceiver != null)
            {
                Android.App.Application.Context.UnregisterReceiver(mReceiver);
            }
            base.OnPause();
        }

        protected override void OnResume()
        {
            base.OnResume();

            if (mReceiver != null)
            {
                Android.App.Application.Context.RegisterReceiver(mReceiver, mFilter);
            }
        }

        protected override void OnDestroy()
        {
            Util.MessagingCenter.Unsubscribe<MyBroadcastReceiver>(this, KEY_RECEIVE);
            base.OnDestroy();
        }

        public override void OnBackPressed()
        {
            // base.OnBackPressed();
        }

        private void initEvent()
        {
            Util.MessagingCenter.Subscribe<MyBroadcastReceiver, string>(this, KEY_RECEIVE, (s, e) =>
            {
                Xamarin.Essentials.MainThread.BeginInvokeOnMainThread(() =>
                {
                    string actionStr = this.txtAction.Text.Trim();
                    string keyOfData = this.txtKeyOfData.Text.Trim();

                    txtScanContent.Text = e;
                    txtScanContentShowSpecialSymbol.Text = e.StringShowSpecialSymbol();

                    txtScanContentLength.Text = $"扫码内容[长度:{e.Length}]:";
                    txtScanTime.Text = $"扫码时间{DateTime.Now.ToString("HH:mm:ss")}";
                });
            });
        }

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }

        List<ScrollView> viewList { get; set; } = new List<ScrollView>();
        int viewListIndex = 0;

        Button btnPreviousView { get; set; }
        Button btnNextView { get; set; }

        void initUI()
        {
            viewList.Add(FindViewById<ScrollView>(Resource.Id.viewScanner));
            viewList.Add(FindViewById<ScrollView>(Resource.Id.viewSendBroadcast));
            viewList.Add(FindViewById<ScrollView>(Resource.Id.viewTcpClient));

            btnPreviousView = FindViewById<Button>(Resource.Id.btnPreviousView);
            btnPreviousView.Click += BtnPreviousView_Click;

            btnNextView = FindViewById<Button>(Resource.Id.btnNextView);
            btnNextView.Click += BtnNextView_Click;

            initUI_viewReceiver();
            initUI_viewSendBroadcast();
            initUI_viewTcpClient();
            initUI_viewService();

            Xamarin.Essentials.MainThread.BeginInvokeOnMainThread(loadSecureStorageDatas);
        }

        private void BtnPreviousView_Click(object sender, EventArgs e)
        {
            viewList.ForEach(i => i.Visibility = Android.Views.ViewStates.Gone);

            viewListIndex = viewListIndex - 1;
            if (viewListIndex < 0)
            {
                viewListIndex = viewList.Count - 1;
            }

            viewList[viewListIndex].Visibility = Android.Views.ViewStates.Visible;
        }

        private void BtnNextView_Click(object sender, EventArgs e)
        {
            viewList.ForEach(i => i.Visibility = Android.Views.ViewStates.Gone);

            viewListIndex = viewListIndex + 1;
            if (viewListIndex >= viewList.Count)
            {
                viewListIndex = 0;
            }

            viewList[viewListIndex].Visibility = Android.Views.ViewStates.Visible;
        }

        #region 接收扫描头信息

        public const string k_ReceiverIntentFilter = "ReceiverIntentFilter";

        public const string k_ReceiverKeyOfData = "ReceiverKeyOfData";

        EditText txtIntentFilter { get; set; }

        EditText txtReceiverKeyOfData { get; set; }

        Button btnUpdateReceiver { get; set; }

        Button btnUnregisterReceiver { get; set; }

        TextView txtScanContent { get; set; }

        TextView txtScanContentShowSpecialSymbol { get; set; }

        TextView txtScanContentLength { get; set; }

        TextView txtScanTime { get; set; }

        Button btnCopyScanContent { get; set; }

        void initUI_viewReceiver()
        {
            txtIntentFilter = FindViewById<EditText>(Resource.Id.txtIntentFilter);

            txtReceiverKeyOfData = FindViewById<EditText>(Resource.Id.txtReceiverKeyOfData);

            btnUpdateReceiver = FindViewById<Button>(Resource.Id.btnUpdateReceiver);
            btnUpdateReceiver.Click += BtnUpdateReceiver_Click;

            btnUnregisterReceiver = FindViewById<Button>(Resource.Id.btnUnregisterReceiver);
            btnUnregisterReceiver.Click += BtnUnregisterReceiver_Click;

            txtScanContent = FindViewById<TextView>(Resource.Id.txtScanContent);
            txtScanContentShowSpecialSymbol = FindViewById<TextView>(Resource.Id.txtScanContentShowSpecialSymbol);
            txtScanContentLength = FindViewById<TextView>(Resource.Id.txtScanContentLength);
            txtScanTime = FindViewById<TextView>(Resource.Id.txtScanTime);

            btnCopyScanContent = FindViewById<Button>(Resource.Id.btnCopyScanContent);
            btnCopyScanContent.Click += BtnCopyScanContent_Click;
        }

        MyBroadcastReceiver mReceiver { get; set; }

        IntentFilter mFilter { get; set; }

        private void BtnUpdateReceiver_Click(object sender, EventArgs e)
        {
            updateReceiver();
        }

        void updateReceiver()
        {
            if (this.txtReceiverKeyOfData.Text.IsNullOrWhiteSpace() == true)
            {
                return;
            }

            if (this.txtIntentFilter.Text.IsNullOrWhiteSpace() == true)
            {
                return;
            }

            StaticInfo.IntentFilter = this.txtIntentFilter.Text.Trim();
            StaticInfo.KeyOfData = this.txtReceiverKeyOfData.Text.Trim();

            if (mReceiver != null)
            {
                Application.Context.UnregisterReceiver(mReceiver);
            }

            mReceiver = new MyBroadcastReceiver(false, StaticInfo.KeyOfData);

            mFilter = new IntentFilter(StaticInfo.IntentFilter);

            Application.Context.RegisterReceiver(mReceiver, mFilter);

            Xamarin.Essentials.SecureStorage.SetAsync(k_ReceiverIntentFilter, StaticInfo.IntentFilter);
            Xamarin.Essentials.SecureStorage.SetAsync(k_ReceiverKeyOfData, StaticInfo.KeyOfData);

            Toast.MakeText(this, "已更新Receiver", ToastLength.Short).Show();
        }


        private void BtnUnregisterReceiver_Click(object sender, EventArgs e)
        {
            unregisterReceiver();
        }

        void unregisterReceiver()
        {
            if (mReceiver == null)
            {
                return;
            }

            Application.Context.UnregisterReceiver(mReceiver);

            mReceiver = null;
            mFilter = null;
        }



        private void BtnCopyScanContent_Click(object sender, EventArgs e)
        {
            if (txtScanContent.Text.IsNullOrWhiteSpace() == true)
            {
                return;
            }

            Xamarin.Essentials.MainThread.BeginInvokeOnMainThread(async () =>
            {
                string text = txtScanContent.Text;
                await Xamarin.Essentials.Clipboard.SetTextAsync(text);
                Toast.MakeText(this, "已复制到剪贴板", ToastLength.Short).Show();
            });
        }

        #endregion

        #region FakeScannerService ( 将扫描头扫描到的内容转发出去 )

        Button btnStartService { get; set; }
        Button btnStopService { get; set; }

        void initUI_viewService()
        {
            btnStartService = FindViewById<Button>(Resource.Id.btnStartService);
            btnStartService.Click += BtnStartService_Click;

            btnStopService = FindViewById<Button>(Resource.Id.btnStopService);
            btnStopService.Click += BtnStopService_Click;

            FakeScannerServiceIntent = new Intent(this, typeof(FakeScannerService));
            FakeScannerServiceIntent.SetAction(FakeScannerService.ACTION_START_SERVICE);

            //stopServiceIntent = new Intent(this, typeof(FakeScannerService));
            //stopServiceIntent.SetAction(FakeScannerService.ACTION_STOP_SERVICE);

            QRCodeCreatorConnectServiceIntent = new Intent(this, typeof(QRCodeCreatorConnectService));
            QRCodeCreatorConnectServiceIntent.SetAction(QRCodeCreatorConnectService.ACTION_START_SERVICE);
        }

        Intent FakeScannerServiceIntent { get; set; }

        //Intent stopServiceIntent { get; set; }

        private void BtnStartService_Click(object sender, EventArgs e)
        {
            string errorMsg = "请设置转发广播";

            if (StaticInfo.ZhuanFaGuangBo.Action.IsNullOrWhiteSpace() == true)
            {
                Toast.MakeText(Application.Context, errorMsg, ToastLength.Long).Show();
                return;
            }

            if (StaticInfo.ZhuanFaGuangBo.Action.IsNullOrWhiteSpace() == true)
            {
                Toast.MakeText(Application.Context, errorMsg, ToastLength.Long).Show();
                return;
            }

            StartService(FakeScannerServiceIntent);
        }

        private void BtnStopService_Click(object sender, EventArgs e)
        {
            // StopService(stopServiceIntent);
            StopService(FakeScannerServiceIntent);
        }

        #endregion

        #region 转发广播

        public const string Key_Action = "ZhuanFaGuangBo_Action";

        public const string Key_KeyOfData = "ZhuanFaGuangBo_KeyOfData";


        EditText txtAction { get; set; }
        EditText txtKeyOfData { get; set; }
        EditText txtKeyOfBarcodeType { get; set; }

        Button btnMadeInChina { get; set; }
        Button btniData { get; set; }
        Button btnZebra { get; set; }
        Button btnZebraSiemens { get; set; }
        Button btnZebraNippon { get; set; }

        void initUI_viewSendBroadcast()
        {
            txtAction = FindViewById<EditText>(Resource.Id.txtAction);
            txtAction.TextChanged += (s, e) =>
            {
                if (StaticInfo.IntentFilter == e.Text.ToString().TrimAdv())
                {
                    Toast.MakeText(Application.Context, "警告!!\r\n接收信息的Intent过滤 与 \r\n转发广播的action\r\n配置相同会导致死循环", ToastLength.Long).Show();
                }

                StaticInfo.ZhuanFaGuangBo.Action = e.Text.ToString().TrimAdv();
                Xamarin.Essentials.SecureStorage.SetAsync(MainActivity.Key_Action, StaticInfo.ZhuanFaGuangBo.Action);
            };

            txtKeyOfData = FindViewById<EditText>(Resource.Id.txtKeyOfData);
            txtKeyOfData.TextChanged += (s, e) =>
            {
                StaticInfo.ZhuanFaGuangBo.KeyOfData = e.Text.ToString().TrimAdv();
                Xamarin.Essentials.SecureStorage.SetAsync(MainActivity.Key_KeyOfData, StaticInfo.ZhuanFaGuangBo.KeyOfData);
            };

            txtKeyOfBarcodeType = FindViewById<EditText>(Resource.Id.txtKeyOfBarcodeType);
            txtKeyOfBarcodeType.TextChanged += (s, e) =>
            {
                StaticInfo.ZhuanFaGuangBo.KeyOfBarcodeType = e.Text.ToString();
                // TODO
            };

            btnMadeInChina = FindViewById<Button>(Resource.Id.btnMadeInChina);
            btnMadeInChina.Click += BtnMadeInChina_Click;

            btniData = FindViewById<Button>(Resource.Id.btniData);
            btniData.Click += BtniData_Click;

            btnZebra = FindViewById<Button>(Resource.Id.btnZebra);
            btnZebra.Click += BtnZebra_Click;

            btnZebraSiemens = FindViewById<Button>(Resource.Id.btnZebraSiemens);
            btnZebraSiemens.Click += BtnZebraSiemens_Click;

            btnZebraNippon = FindViewById<Button>(Resource.Id.btnZebraNippon);
            btnZebraNippon.Click += BtnZebraNippon_Click;
        }

        private void BtnMadeInChina_Click(object sender, EventArgs e)
        {
            txtAction.Text = "com.android.server.scannerservice.broadcast";
            txtKeyOfData.Text = "scannerdata";
            txtKeyOfBarcodeType.Text = "";
        }

        private void BtniData_Click(object sender, EventArgs e)
        {
            txtAction.Text = "android.intent.action.SCANRESULT";
            txtKeyOfData.Text = "value";
            txtKeyOfBarcodeType.Text = "";
        }

        private void BtnZebra_Click(object sender, EventArgs e)
        {
            txtAction.Text = "com.symbol.datawedge.api.ACTION";
            txtKeyOfData.Text = "com.symbol.datawedge.data_string";
            txtKeyOfBarcodeType.Text = "com.symbol.datawedge.label_type";
        }

        private void BtnZebraSiemens_Click(object sender, EventArgs e)
        {
            txtAction.Text = "com.enpot.siemens.labelscan";
            txtKeyOfData.Text = "com.symbol.datawedge.data_string";
            txtKeyOfBarcodeType.Text = "com.symbol.datawedge.label_type";
        }

        private void BtnZebraNippon_Click(object sender, EventArgs e)
        {
            txtAction.Text = "com.enpot.libang";
            txtKeyOfData.Text = "com.symbol.datawedge.data_string";
            txtKeyOfBarcodeType.Text = "com.symbol.datawedge.label_type";
        }

        public static void RunZhuanFaGuangBo(string data)
        {
            // TODO Barcode Type

            ZhuanFaGuangBo
            (
                StaticInfo.ZhuanFaGuangBo.Action,
                StaticInfo.ZhuanFaGuangBo.KeyOfData,
                data
            );
        }

        public static void ZhuanFaGuangBo(string action, string keyOfData, string data, string packageName = null, string keyOfBarcodeType = null, string barcodeType = null)
        {
            var intent = new Intent();
            intent.SetAction(action);

            if (packageName.IsNullOrEmpty() == false)
            {
                intent.SetPackage(packageName); // 指定广播接收的包名, 可以不设置, 任何包都能收到此广播
            }

            intent.PutExtra(name: keyOfData, value: data);

            if (keyOfBarcodeType.IsNullOrEmpty() == false && barcodeType.IsNullOrEmpty() == false)
            {
                intent.PutExtra(name: keyOfBarcodeType, value: barcodeType);
            }

            Application.Context.SendBroadcast(intent);
        }

        #endregion

        #region 连接PC - QRCodeCreator

        public const string k_IP = "IP";

        public const string k_Port = "Port";

        EditText txtIP { get; set; }
        EditText txtPort { get; set; }

        Button btnStart { get; set; }
        Button btnStop { get; set; }

        Intent QRCodeCreatorConnectServiceIntent { get; set; }

        void initUI_viewTcpClient()
        {
            txtIP = FindViewById<EditText>(Resource.Id.txtIP);
            txtIP.TextChanged += (s, e) => { StaticInfo.QRCodeCreatorConnect.IP = e.Text.ToString(); };

            txtPort = FindViewById<EditText>(Resource.Id.txtPort);
            txtPort.TextChanged += (s, e) => { StaticInfo.QRCodeCreatorConnect.Port = e.Text.ToString(); };

            btnStart = FindViewById<Button>(Resource.Id.btnStart);
            btnStart.Click += BtnStart_Click;

            btnStop = FindViewById<Button>(Resource.Id.btnStop);
            btnStop.Click += BtnStop_Click;
        }

        private void BtnStart_Click(object sender, System.EventArgs e)
        {
            if (string.IsNullOrEmpty(StaticInfo.QRCodeCreatorConnect.IP))
            {
                Toast.MakeText(this, "请填写IP", ToastLength.Long).Show();
                return;
            }

            if (string.IsNullOrEmpty(StaticInfo.QRCodeCreatorConnect.Port))
            {
                Toast.MakeText(this, "请填写Port", ToastLength.Long).Show();
                return;
            }

            var current = Xamarin.Essentials.Connectivity.NetworkAccess;
            if (current == Xamarin.Essentials.NetworkAccess.None)
            {
                string msg = "检测设备没有可用的网络，请开启 数据 或 Wifi。";
                Toast.MakeText(this, msg, ToastLength.Long).Show();
                return;
            }

            StartService(QRCodeCreatorConnectServiceIntent);
        }

        private void BtnStop_Click(object sender, System.EventArgs e)
        {
            StopService(QRCodeCreatorConnectServiceIntent);
        }

        #endregion

        async void loadSecureStorageDatas()
        {
            StaticInfo.IntentFilter = await Xamarin.Essentials.SecureStorage.GetAsync(k_ReceiverIntentFilter);
            if (StaticInfo.IntentFilter.IsNullOrWhiteSpace() == false)
            {
                txtIntentFilter.Text = StaticInfo.IntentFilter;
            }

            StaticInfo.KeyOfData = await Xamarin.Essentials.SecureStorage.GetAsync(k_ReceiverKeyOfData);
            if (StaticInfo.KeyOfData.IsNullOrWhiteSpace() == false)
            {
                txtReceiverKeyOfData.Text = StaticInfo.KeyOfData;
            }

            if (StaticInfo.IntentFilter.IsNullOrWhiteSpace() == false && StaticInfo.KeyOfData.IsNullOrWhiteSpace() == false)
            {
                updateReceiver();
            }

            #region 转发广播

            StaticInfo.ZhuanFaGuangBo.Action = await Xamarin.Essentials.SecureStorage.GetAsync(Key_Action);
            if (StaticInfo.ZhuanFaGuangBo.Action.IsNullOrWhiteSpace() == false)
            {
                txtAction.Text = StaticInfo.ZhuanFaGuangBo.Action;
            }

            StaticInfo.ZhuanFaGuangBo.KeyOfData = await Xamarin.Essentials.SecureStorage.GetAsync(Key_KeyOfData);
            if (StaticInfo.ZhuanFaGuangBo.KeyOfData.IsNullOrWhiteSpace() == false)
            {
                txtKeyOfData.Text = StaticInfo.ZhuanFaGuangBo.KeyOfData;
            }

            // 待加上 Barcode Type

            #endregion

            StaticInfo.QRCodeCreatorConnect.IP = await Xamarin.Essentials.SecureStorage.GetAsync(k_IP);
            if (StaticInfo.QRCodeCreatorConnect.IP.IsNullOrWhiteSpace() == false)
            {
                txtIP.Text = StaticInfo.QRCodeCreatorConnect.IP;
            }

            StaticInfo.QRCodeCreatorConnect.Port = await Xamarin.Essentials.SecureStorage.GetAsync(k_Port);
            if (StaticInfo.QRCodeCreatorConnect.Port.IsNullOrWhiteSpace() == false)
            {
                txtPort.Text = StaticInfo.QRCodeCreatorConnect.Port;
            }
        }
    }
}